package com.josn.messagewall.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtUtil {

    @Value("${jwt.key}")
    private String secreatkey;//密钥

    @Value("${jwt.time}")
    private Integer time; //过期时间

    /**
     * 生成token
     */
    public String getToken(String userId) {
        // 设置过期时间
        Date expiresAt = new Date(System.currentTimeMillis() + time);
        //设置加密算法
        Algorithm algorithm = Algorithm.HMAC256(secreatkey);

        String token = JWT.create()
                .withSubject(userId)// 设置主题 (Subject), 通常是用户ID
                .withExpiresAt(expiresAt)// 设置过期时间
                .sign(algorithm);// 使用算法签名
        return token;
    }

    /**
     * 解析token
     */
    public boolean parseToken(String token) {
        // 设置加密算法
        Algorithm algorithm = Algorithm.HMAC256(secreatkey);
        // 创建验证器
        JWTVerifier verifier = JWT.require(algorithm)
                .build();
        try {
            DecodedJWT verify = verifier.verify(token);
        } catch (JWTVerificationException e) {
            return false;
        }
        return true;
    }
}
